<?php
class PresentationFormattedRelation extends Presentation {
    protected $table;
    protected $primaryKey;
    protected $format;
    protected $canBeNull;
    protected $fields;
    
    public function __construct($table, $primaryKey, $format,
            $canBeNull = false) {
        $this->table = $table;
        $this->primaryKey = $primaryKey;
        $this->format = $format;
        $this->canBeNull = $canBeNull;
        $this->loadFields();
    }
    
    public function fixInput($current, $rawInput) {
        if (!$rawInput && $this->canBeNull) {
            return null;
        }
        return $current;
    }
    
    public function formatFormField(&$field) {
        $field['type'] = 'select';
        $options = array();
        $this->canBeNull && ($options[''] = '---');
        $order = array($this->primaryKey);
        $cols = $this->getCols();
        $data = &$this->dbdriver->select($this->table, $cols, '',
                $order);
        foreach ($data as &$row) {
            $options[$row[$this->primaryKey]] = $this->format($row);
        }
        $field['options'] = &$options;
        $field['selected'] = $field['value'];
    }
    
    public function formatForList($value) {
        if (!$value) {
            return '---';
        }
        $value = &$this->dbdriver->select($this->table, $this->fields,
                '`' . $this->primaryKey . '` = ' . (int) $value);
        return isset($value[0]) ? $this->format($value[0]) : '---';
    }
    
    protected function format(&$values) {
        $str = $this->format;
        foreach ($this->fields as $field) {
            $str = str_replace('{$' . $field . '}', $values[$field], $str);
        }
        return $str;
    }
    
    protected function getCols() {
        return array_merge(array($this->primaryKey), $this->fields);
    }
    
    protected function loadFields() {
        preg_match_all('/[{][$]([^}]+)[}]/', $this->format, $fields);
        $this->fields = $fields[1];
    }
}